const crypto = require('crypto-js');

/**
 * 加密
 * @param originalText 原始文本
 * @param secretKey 密钥
 * @returns {string} 加密后的文本
 */
const encrypt = (originalText, secretKey) => {
  const key = crypto.enc.Utf8.parse(secretKey);
  const encrypted = crypto.AES.encrypt(originalText, key, {
    mode: crypto.mode.ECB,
    padding: crypto.pad.Pkcs7
  });
  return encrypted.ciphertext.toString();
};

/**
 * 解密
 * @param cipherText 密文
 * @param secretKey 密钥
 * @returns {string} 解密后的文本
 */
const decrypt = (cipherText, secretKey) => {
  const ckey = crypto.enc.Utf8.parse(secretKey);
  const ciphertext = crypto.enc.Hex.parse(cipherText);
  const srcs = crypto.enc.Base64.stringify(ciphertext);
  const decrypt = crypto.AES.decrypt(srcs, ckey, {
    mode: crypto.mode.ECB,
    padding: crypto.pad.Pkcs7
  });
  const decrypted = decrypt.toString(crypto.enc.Utf8);
  return decrypted.toString(crypto.enc.Utf8);
};

/**
 * 前端解密函数
 * @param {*} cipherText 
 * @returns {string} 解密后的明文
 */
const frontDecrypt = (cipherText) => {
  return decrypt(cipherText, process.env.FRONTEND_KEY)
}

/**
 * 后端加密函数
 * @param {*} cipherText 
 * @returns {string} 加密后的密文
 */
const backEncrypt = (cipherText) => {
  return encrypt(cipherText, process.env.BACKEND_KEY)
}

/**
 * 后面解密函数
 * @param {*} cipherText 
 * @returns {string} 解密后的明文
 */
const backDecrypt = (cipherText) => {
  return decrypt(cipherText, process.env.BACKEND_KEY)
}

module.exports = {
  frontDecrypt,
  backEncrypt,
  backDecrypt
}